<template>
  <div class="full">
    <ul class="dis-flex flex-y-center flex-x-center tags">
      <li v-for="(item,index) in tagsList" :key="index" class="tags-li dis-flex flex-y-center flex-x-center" :class="{'active': isActive(item.path)}">
        <router-link :to="item.path" class="tags-li-title">
          {{ item.title }}
        </router-link>
        <span class="tags-li-icon" @click="closeTags(index)"><i class="el-icon-close" /></span>
      </li>
    </ul>
  </div>
</template>
<script>
import bus from '@/utils/bus'
export default {
  name: 'Tags',
  data() {
    return {
      tagsList: []
    }
  },
  watch: {
    $route(newValue, oldValue) {
      this.setTags(newValue)
    }
  },
  mounted() {
    this.setTags(this.$route)
  },
  methods: {
    // 判断是否为当前路由
    isActive(path) {
      return path === this.$route.fullPath
    },
    // 关闭单个标签
    closeTags(index) {
      const delItem = this.tagsList.splice(index, 1)[0]
      const item = this.tagsList[index] ? this.tagsList[index] : this.tagsList[index - 1]
      if (item) {
        delItem.path === this.$route.fullPath && this.$router.push(item.path)
      } else {
        this.$router.push('/')
      }
      bus.$emit('tags', this.tagsList)
    },
    // 设置标签
    setTags(route) {
      const isExist = this.tagsList.some(item => {
        return item.path === route.fullPath
      })

      if (!isExist) {
        // 标签最多可存在8个
        if (this.tagsList.length >= 8) {
          this.tagsList.shift()
        }
        // 为了将页面路径相同但是传参不同的缓存删除
        this.tagsList = this.tagsList.filter(item => (item.name !== route.name))
        this.tagsList.push({
          title: route.meta.title,
          path: route.fullPath,
          name: route.name
        })
      }
      // 将标签内的页面名称   存入缓存中
      bus.$emit('tags', this.tagsList)
    }
  }
}
</script>
<style lang="scss" scoped>
.full{
  height: 100%;
  .tags{
  list-style: none;
  margin: 0;
   height: 100%;
   padding: 0;
   font-size: 14px;
   font-weight: 600;
   color: #666666;
   &-li{
     min-width: 100px;
     text-align: center;
     height: 100%;
     position: relative;
     &-icon{
       position: absolute;
       right: 0;
       top: 0;
       display: none;
     }
   }
    &-li:hover .tags-li-icon{
       display: block;
     }
   .active{
     background: #F0F0F0;
     color: #0091FF;
     border-bottom: 2px solid #0091FF;
   }
  }
}

</style>
